﻿using System;
using System.Linq;
using System.Windows;

namespace TestUI
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        CyUsbWrapper.CyUsbWrapper _usb;

        public MainWindow()
        {
            InitializeComponent();
            //System.Threading.ThreadPool.QueueUserWorkItem(obj => { while (true) _testTimer_Elapsed(); });
        }

        double r = 0;
        private void _testTimer_Elapsed()
        {
               var v = (uint)(Math.Sin(r) *10000);
                r += 0.001;
                AddToCurve(v);
            //System.Threading.Thread.Sleep(1);
        }

        private void OpenDevice_Click(object sender, RoutedEventArgs e)
        {
            _usb = CyUsbWrapper.CyUsbWrapper.Instance;
           // _usb.OnGetData = OnGetData;
            var rval = _usb.OpenDevice();
            MessageBox.Show(string.Format("open device {0}!", rval ? "success" : "falied"));
        }

        public int SelectedChannel { get; set; }
        private int _selectedHz;
        public int SelectedHz
        {
            get { return _selectedHz; }
            set { _selectedHz = value;
                _samplingRate = (int)Math.Pow(2, value);
                Console.WriteLine("samplingRate = {0}", _samplingRate);

            }
        }

        void OnGetData(uint[] arr)
        {
            var curveArr = arr.Where(val => (val >> 12) == SelectedChannel);
            foreach(var val in curveArr)
            {
                AddToCurve(val);
            }

            Console.WriteLine("ui get data. selected channel = {0}, data length = {1}", SelectedChannel, curveArr.Count());
        }
        private void RegsReadWrite_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var laddr = (byte)Convert.ToInt32(addr.Text, 16);
                var ldata = (ushort)Convert.ToInt32(rwdata.Text, 16);
                var rval = _usb.RegsReadWrite(rwflag.Text == "r", laddr, ldata);
                rwdata.Text = string.Format("{0:X}", rval);
                MessageBox.Show(string.Format("regs read write {0}!", rval > 0 ? "success" : "falied"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void StartAcq_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var rval = _usb.StartAcq();
                MessageBox.Show(string.Format("start acq {0}!", rval ? "success" : "falied"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void StopAcq_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var rval = _usb.StopAcq();
                MessageBox.Show(string.Format("stop acq {0}!", rval ? "success" : "falied"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void DataRecv_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var llen = int.Parse(length.Text);
                var rval = _usb.DataRecv(dataRecvPath.Text, llen);
                MessageBox.Show(string.Format("data recv {0}!", rval ? "success" : "falied"));
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

        private void SaveData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var lpath = path.Text;
                var thd = new System.Threading.Thread(() => { _usb.SaveData(lpath); });
                thd.Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }


        volatile int _samplingRate = 1;
        int count = 0;

        const int maxCacheCount = 16;
        uint[] cache = new uint[maxCacheCount];
        int cacheCount = 0;
        void AddToCurve(uint val)
        {
            if (++count == _samplingRate)
            {
                cache[cacheCount] = val;
                cacheCount++;
                if(cacheCount == maxCacheCount)
                {
                    this.curve.AddValue(cache);
                    cacheCount = 0;
                }

                count = 0;
            }
        }

        private void OpenFile_Button_Click(object sender, RoutedEventArgs e)
        {
            var dlg = new Microsoft.Win32.OpenFileDialog();
            if (dlg.ShowDialog() == true)
            {
                System.Threading.ThreadPool.QueueUserWorkItem(obj =>
                {
                    try
                    {
                        using (var f = new System.IO.FileStream(dlg.FileName, System.IO.FileMode.Open))
                        {
                            var br = new System.IO.BinaryReader(f);

                            while (true)
                            {
                                var val = br.ReadUInt32();
                                AddToCurve(val);
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                });
            }
            
        }
    }
}
